/************************************************************************
This file is part of Polar4linux
Copyright (C) 2010-2011 Eric jrdn2
Portions Copyright (C) 2007 Matti Juvonen <mpj@iki.fi> (RS400 Tools)
Portions Copyright (C) 2006 Jani Hursti <jani.hursti@hut.fi>,
Portions Copyright (C) 2001-2003 Tom Oliveira e Silva

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
************************************************************************/

#include "polarSpreadsheet.h"
polarSpreadsheet::polarSpreadsheet(polar4linuxInternals *internals0)
{
	currentEx=-1;
	setupUi(this);
	
	internals=internals0;
	connect(pushButtonSaveAscii, SIGNAL(clicked()), this, SLOT(saveAscii()));
	connect(comboBoxExercise, SIGNAL(currentIndexChanged ( int )), this, SLOT(displayExercise(int)) );

	connect(SpinBoxWeight,						SIGNAL(valueChanged ( double)), this, SLOT(updateDescription()));
	connect(timeEditSleepingHours,		SIGNAL(timeChanged ( const QTime &)), this, SLOT(updateDescription()));
	connect(comboBoxSleepingType,			SIGNAL(currentIndexChanged ( int )), this, SLOT(updateDescription()));
	connect(comboBoxWeather,					SIGNAL(currentIndexChanged ( int )), this, SLOT(updateDescription()));
	connect(doubleSpinBoxTemperature, SIGNAL(valueChanged ( double)), this, SLOT(updateDescription()));
	connect(checkBoxTravelling, 			SIGNAL(stateChanged ( int )), this, SLOT(updateDescription()));
	connect(checkBoxMatch, 						SIGNAL(stateChanged ( int )), this, SLOT(updateDescription()));
	connect(checkBoxFitness, 					SIGNAL(stateChanged ( int )), this, SLOT(updateDescription()));
	connect(checkBoxMassage, 					SIGNAL(stateChanged ( int )), this, SLOT(updateDescription()));
	connect(checkBoxSick, 						SIGNAL(stateChanged ( int )), this, SLOT(updateDescription()));
	connect(checkBoxInjured, 					SIGNAL(stateChanged ( int )), this, SLOT(updateDescription()));
	connect(timeEditStartTime, 				SIGNAL(timeChanged ( const QTime &)), this, SLOT(updateDescription()));
	connect(comboBoxFeeling, 					SIGNAL(currentIndexChanged ( int )), this, SLOT(updateDescription()));
	connect(comboBoxRecovery, 				SIGNAL(currentIndexChanged ( int )), this, SLOT(updateDescription()));
	connect(plainTextEditNote, 				SIGNAL(textChanged ()), this, SLOT(updateDescription()));

	tableWidget->horizontalHeader()->setStretchLastSection( true ); 
}

void polarSpreadsheet::updateDescription()
{
	if (currentEx!=-1) saveExercise(currentEx);
}

//just put the widget in its initial state for later use
void polarSpreadsheet::invalidate()
{
	currentEx=-1;
	comboBoxExercise->clear();
	hrm_list.clear();
	hide();
}

void polarSpreadsheet::leaveEvent ( QEvent * event )
{
	internals->plotW->view->plotPage();
}

void polarSpreadsheet::closeEvent ( QCloseEvent * event )
{
	internals->plotW->view->plotPage();
}


void polarSpreadsheet::updateExerciseList()
{
	currentEx=-1;
	comboBoxExercise->clear();
	hrm_list.clear();
	for (unsigned int i=0;i<internals->plotW->NumberOfGraphs();i++)
	{
		sessionGraph* sGr=dynamic_cast<sessionGraph*> (internals->plotW->graphNumber(i));
		if (sGr)
		{
		for (unsigned int j=0;j<sGr->dataSize();j++)
		{
				QString label = tr("graph ")+QString::number(i)+tr(", exercise ")+QString::number(j);
				comboBoxExercise->insertItem(i,label);
				hrm_list.push_back(&sGr->dataNumber(j));
		}
		}
	}
	displayExercise(0);
}


void polarSpreadsheet::saveExercise(int exNum)
{
	if (exNum<hrm_list.size())
	{
		hrm_data *data=hrm_list[exNum];
		rs400_session *session=data->session;
		rs400_pdd_content *pddContent=data->pddContent;
		rs400_pdd_day_info *dayinfo=&pddContent->dayinfo;
		rs400_pdd_exercise_info *exinfo=&pddContent->exerciseinfo[data->exNumberForToday];
		
		//day info
		dayinfo->weight=SpinBoxWeight->value()*100.0;
		dayinfo->sleepingHours=timeEditSleepingHours->time().hour()*3600+timeEditSleepingHours->time().minute()*60;
		dayinfo->sleepingPattern=comboBoxSleepingType->currentIndex();
		dayinfo->weather=comboBoxWeather->currentIndex();
		dayinfo->temperature=doubleSpinBoxTemperature->value()*100;
		
		dayinfo->dayInfoData=checkBoxTravelling->isChecked()*0x01+checkBoxMatch->isChecked()*0x32+checkBoxFitness->isChecked()*0x04+checkBoxMassage->isChecked()*0x02+checkBoxSick->isChecked()*0x16+checkBoxInjured->isChecked()*0x08;
		
		
		//exercise
		session->start_hour=timeEditStartTime->time().hour();
		session->start_minute=timeEditStartTime->time().minute();
		session->start_second=timeEditStartTime->time().second();
		exinfo->startTime=timeEditStartTime->time().hour()*3600+timeEditStartTime->time().minute()*60+timeEditStartTime->time().second();
		
		exinfo->feeling=comboBoxFeeling->currentIndex();
		exinfo->recovery=comboBoxRecovery->currentIndex();
		QString comment = plainTextEditNote->toPlainText();

		//remove \r \n
		for (unsigned int i=0;i<comment.size();i++)
		{
			if (comment[i]=='\r' || comment[i]=='\n') comment[i]=' ';
		}
		std::string comment2=comment.toStdString();
		comment2.resize(250);
		
		strcpy(session->comment,comment2.c_str());
		
		data->has_changed=1;
	}
}

void polarSpreadsheet::displayExercise(int exNum)
{
	if (exNum<hrm_list.size())
	{
		//displayExercise() triggers each widget valueChanged() signal
		//force these not to save data during this process
		currentEx=-1;

		const hrm_data *data=hrm_list[exNum];
		const rs400_session *session=data->session;
		const rs400_pdd_content *pddContent=data->pddContent;
		const rs400_pdd_day_info *dayinfo=&pddContent->dayinfo;
		const rs400_pdd_exercise_info *exinfo=&pddContent->exerciseinfo[data->exNumberForToday];
		
		//day info:
		dateEditDate->setDate(QDate(session->year,session->month,session->day));
		SpinBoxWeight->setValue(dayinfo->weight/100.0);
		int tmp=dayinfo->sleepingHours;
		int h=tmp/3600;
		int m=(tmp-h*60)/60;
		int s=tmp-h*3600-m*60;
		timeEditSleepingHours->setTime (QTime(h,m,s));
		comboBoxSleepingType->setCurrentIndex(dayinfo->sleepingPattern);
		comboBoxWeather->setCurrentIndex(dayinfo->weather);
		doubleSpinBoxTemperature->setValue(dayinfo->temperature/100.0f);
		
		checkBoxTravelling->setChecked(dayinfo->dayInfoData&0x01);
		checkBoxSick->setChecked(dayinfo->dayInfoData&0x10);
		checkBoxInjured->setChecked(dayinfo->dayInfoData&0x08);
		checkBoxFitness->setChecked(dayinfo->dayInfoData&0x04);
		checkBoxMassage->setChecked(dayinfo->dayInfoData&0x02);
		checkBoxMatch->setChecked(dayinfo->dayInfoData&0x20);
		
		//exercise info
		timeEditStartTime->setTime (QTime(session->start_hour,session->start_minute,session->start_second));
		comboBoxFeeling->setCurrentIndex(exinfo->feeling);
		comboBoxRecovery->setCurrentIndex(exinfo->recovery);
		plainTextEditNote->setPlainText (QString(data->session->comment));

		//laps info
		unsigned int nblaps=data->session->number_of_laps;
		tableWidget->clearContents ();
		tableWidget->setColumnCount(7);
		tableWidget->setRowCount(nblaps);
		
		QStringList colNames;
		colNames << tr("Start time")<<tr("Duration")<<tr("HR (avg)")<<tr("HR (min)")<<tr("HR (max)")<<tr("HR (end)")<<tr("Comment");
		
		tableWidget->setHorizontalHeaderLabels(colNames);
	
		for (int k=0;k<(int)nblaps;k++)
		{
			double first=data->session->lap[k].lap_end_time-data->session->lap[k].laptime;
			double dur=data->session->lap[k].laptime;
			char duration[12];
			char start[12];

			timetostr(start, first);
			timetostr(duration, dur);
		
			QTableWidgetItem *Item = new QTableWidgetItem(QString(start));
			QTableWidgetItem *Item2 = new QTableWidgetItem(QString(duration));
			QTableWidgetItem *Item3 = new QTableWidgetItem(QString::number(data->session->lap[k].hr_avg));
			QTableWidgetItem *Item4 = new QTableWidgetItem(QString::number(data->session->lap[k].hr_min));
			QTableWidgetItem *Item5 = new QTableWidgetItem(QString::number(data->session->lap[k].hr_max));
			QTableWidgetItem *Item6 = new QTableWidgetItem(QString::number(data->session->lap[k].hr_end));
			QTableWidgetItem *Item7 = new QTableWidgetItem(QString(data->session->lap[k].note));
			tableWidget->setItem(k, 0, Item);
			tableWidget->setItem(k, 1, Item2);
			tableWidget->setItem(k, 2, Item3);
			tableWidget->setItem(k, 3, Item4);
			tableWidget->setItem(k, 4, Item5);
			tableWidget->setItem(k, 5, Item6);
			tableWidget->setItem(k, 6, Item7);
		}
		currentEx=exNum;
	}
}

void polarSpreadsheet::saveAscii()
{
	QString FilePath = QFileDialog::getSaveFileName(this,tr("Save laps"), tr("laps.txt"), tr("text Files (*.txt)"));
  if(FilePath.isEmpty()) return;
	std::ofstream fichier(FilePath.toStdString().c_str());
	
	int exNum = comboBoxExercise->currentIndex();
	hrm_data *data=hrm_list[exNum];
	rs400_session *session=data->session;
	
	unsigned int nblaps=data->session->number_of_laps;
	for (int k=0;k<(int)nblaps;k++)
	{
		double first=data->session->lap[k].lap_end_time-data->session->lap[k].laptime;
		double dur=data->session->lap[k].laptime;
		char duration[12];
		char start[12];

		timetostr(start, first);
		timetostr(duration, dur);
		
		fichier<<start<<" "<<duration<<" "<<data->session->lap[k+1].hr_avg<<" "<<data->session->lap[k+1].hr_min<<" ";
		fichier<<data->session->lap[k+1].hr_max<<" "<<data->session->lap[k+1].hr_end<<" "<<data->session->lap[k+1].note;
		fichier<<std::endl;
	}
	fichier.close();
}
